﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Flurl.Http;
using Pay.Core;
using Pay.DTO;
using Pay.DTO.chpay;
using Pay.IService;
using Pay.TO;

namespace Pay.Service {
    public class ChPayService : ServiceBase2, IPayService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        private ISettingService _iSettingService;
        private IMerchantService _iMerchantService;
        private IChargeService _iChargeService;
        private ITransferService _iTransferService;
        private IProfitDayService _iProfitDayService;
        private IBillService _iBillService;
        private IPayHtmlService _iPayHtmlService;
        private IRegionService _iRegionService;
        private ITokenTransferService _iTokenTransferService;
        private ChPaySign _chPaySign;

        public ChPayService(IUnitOfWork iUnitOfWork, ISettingService iSettingService, IMerchantService iMerchantService, IChargeService iChargeService,
                            ITransferService iTransferService, IProfitDayService iProfitDayService, IBillService iBillService,
                            IPayHtmlService iPayHtmlService, IRegionService iRegionService, ITokenTransferService iTokenTransferService) : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
            _iSettingService = iSettingService;
            _iMerchantService = iMerchantService;
            _iChargeService = iChargeService;
            _iTransferService = iTransferService;
            _iProfitDayService = iProfitDayService;
            _iBillService = iBillService;
            _iPayHtmlService = iPayHtmlService;
            _iRegionService = iRegionService;
            _iTokenTransferService = iTokenTransferService;
            _chPaySign = new ChPaySign();
        }

        #region 扫码的
        /// <summary>
        /// 生成二维码扫码请求通道封装
        /// </summary>
        /// <returns>The pay gateway.</returns>
        /// <param name="model">Model.</param>
        /// <typeparam name="T">The 1st type parameter.</typeparam>
        public Task<native_result> NativePay(native_model model) {
            throw new NotImplementedException();
        }
        #endregion

        #region 支付异步通知
        /// <summary>
        /// 回调支付通知，商户返回OK，不再回调了，流程是先调用ChargeService的NotifyOrder，
        /// 返回值判断是调用哪个通道，再调用本方法，最后调用ChargeService的Update
        /// </summary>
        /// <returns>The notify.</returns>
        /// <param name="order_no">Order.</param>
        public Task<string> Notify(string merchant_no, string order_no) {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 代付通知－不可用
        /// </summary>
        /// <returns>The transfer.</returns>
        /// <param name="order_no">Order.</param>
        public async Task<string> NotifyTransfer(string merchant_no, string order_no) {
            string result = string.Empty;
            var transfer = _iTransferService.Get(merchant_no, order_no);
            if (transfer == null) return "OK";
            try {
                //var setting = transfer.merchant.setting;
                var data = new transfer_result {
                    order_no = transfer.order_no, transaction_no = transfer.pay_info.transaction_no,
                    pay_time = transfer.pay_info.pay_time.HasValue ? transfer.pay_info.pay_time.Value : transfer.apply_time
                };
                if (transfer.status == TransferStatus.UnConfirm) data.status = 2;
                else if (transfer.status == TransferStatus.Fail) data.status = 3;
                else if (transfer.status == TransferStatus.Finish) data.status = 1;
                //不确定的要再查询通道判断是否有结果了,处理掉单
                string msg = transfer.fail;
                data.result_msg = data.status == 1 ? "提现成功" : msg;
                if (!string.IsNullOrEmpty(transfer.notify)) {
                    var notify_result = await transfer.notify.PostJsonAsync(ApiResultToJson.Json(data)).ReceiveJson<ResultMessage<string>>();
                    result = notify_result.data;
                    var log = IocHelper.Get<ILogHelper>("info");
                    log.Info(transfer.order_no + ":" + notify_result.ToJson());
                } else
                    result = "OK";
            } catch (Exception ex) {
                var log = IocHelper.Get<ILogHelper>("info");
                log.Error("代付通知异常:" + transfer.order_no);
                log.Error(ex.Message);
            }
            return result;
        }
        #endregion

        #region 实名、T0额度-不可用
        /// <summary>
        /// 查询代付T0额度
        /// </summary>
        /// <returns>The quota.</returns>
        /// <param name="merchant_no"></param>
        /// <param name="busiType">0：对公 1：对私</param>
        public async Task<quota_result> Quota(string merchant_no, string busiType) {
            var result = new quota_result();
            var pay_model = new ch_account_query { accountnumber = ChPaySign.accountnumber };
            var apiResult = await _chPaySign.PayGateway<ch_account_result>(pay_model);
            if (apiResult != null && apiResult.result == "success") {
                result.total = apiResult.data.balance;
                result.balance = apiResult.data.usableBalance;
            }
            return result;
        }
        #endregion

        #region 快捷同卡同出
        /// <summary>
        /// 快捷支付
        /// </summary>
        /// <returns>The receive.</returns>
        /// <param name="model">Model.</param>
        public Task<quick_pay_result> QuickPay(quick_pay_model model) {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 快捷支付查询
        /// </summary>
        /// <returns>The pay query.</returns>
        /// <param name="model">Model.</param>
        public Task<pay_notity> QuickPayQuery(refund_model_query model) {
            throw new NotImplementedException();
        }
        #endregion

        #region 快捷支付－不可用
        /// <summary>
        /// 快捷支付鉴权成功后发短信
        /// </summary>
        /// <returns>The pay resms.</returns>
        /// <param name="model">model.</param>
        public Task<ApiResultMessage> QuickPaySendsms(quick_sendsms_model model) {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 确认短信验证码
        /// </summary>
        /// <returns>The pay.</returns>
        /// <param name="model">model.</param>
        public Task<quick_pay_result> QuickPay(quick_sms_model model) {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 快捷支付退款
        /// </summary>
        /// <returns>The pay refund.</returns>
        /// <param name="model">Model.</param>
        public Task<refund_result> QuickPayRefund(refund_model model) {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 快捷支付退款查询,并将退款中的单处理为完成
        /// </summary>
        /// <returns>The pay refund.</returns>
        /// <param name="model">Model.</param>
        public Task<refund_result> QuickPayRefundQuery(refund_model_query model) {
            throw new NotImplementedException();
        }
        #endregion

        #region 网关支付-不可用
        /// <summary>
        /// 网关支付银行
        /// </summary>
        /// <returns>The pay bank.</returns>
        public List<type_setting> GatewayPayBank() {
            var banks = new List<type_setting>();
            banks.Add(new type_setting { value = "BOC", text = "中国银行" });
            banks.Add(new type_setting { value = "ABC", text = "中国农业银行" });
            banks.Add(new type_setting { value = "ICBC", text = "中国工商银行" });
            banks.Add(new type_setting { value = "CCB", text = "中国建设银行" });
            banks.Add(new type_setting { value = "COMM", text = "交通银行" });
            banks.Add(new type_setting { value = "PSBC", text = "中国邮政储蓄银行" });
            banks.Add(new type_setting { value = "CMB", text = "招商银行" });
            banks.Add(new type_setting { value = "CMBC", text = "中国民生银行" });
            banks.Add(new type_setting { value = "CITIC", text = "中信银行" });
            banks.Add(new type_setting { value = "CEB", text = "中国光大银行" });
            banks.Add(new type_setting { value = "HXB", text = "华夏银行" });
            banks.Add(new type_setting { value = "GDB", text = "广发银行" });
            banks.Add(new type_setting { value = "CIB", text = "兴业银行" });
            banks.Add(new type_setting { value = "SPDB", text = "上海浦东发展银行" });
            banks.Add(new type_setting { value = "SPAB", text = "平安银行" });
            banks.Add(new type_setting { value = "SHB", text = "上海银行" });
            banks.Add(new type_setting { value = "BJB", text = "北京银行" });
            banks.Add(new type_setting { value = "HZCB", text = "杭州银行" });
            return banks;
        }

        /// <summary>
        /// 发起网关支付
        /// </summary>
        /// <returns>The receive.</returns>
        /// <param name="model">Model.</param>
        public Task<gateway_pay_result> GatewayPay(gateway_pay_model model) {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 网关支付查询
        /// </summary>
        /// <returns>The pay query.</returns>
        /// <param name="model">Model.</param>
        public Task<pay_notity> GatewayPayQuery(refund_model_query model) {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 网关支付退款
        /// </summary>
        /// <returns>The pay refund.</returns>
        /// <param name="model">Model.</param>
        public Task<refund_result> GatewayPayRefund(refund_model model) {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 网关支付退款查询,并将退款中的单处理为完成
        /// </summary>
        /// <returns>The pay refund.</returns>
        /// <param name="model">Model.</param>
        public Task<refund_result> GatewayRefundQuery(refund_model_query model) {
            throw new NotImplementedException();
        }
        #endregion

        #region 代付,T+0转账
        /// <summary>
        /// 单笔代付
        /// </summary>
        /// <returns>The transfer.</returns>
        /// <param name="model">Model.</param>
        public async Task<transfer_result> Transfer(apply_transfer model) {
            if (model.settle_type == "T0") {
                var setting = _iSettingService.Get();
                var backurl = setting.site.api_url + "/pay/chpay_transfer_notify/" + model.merchant_no;
                var result = _iTransferService.ApplyTransfer(model);
                var binder = _iMerchantService.Get(model.bind_no);
                var auth_info = binder.setting.auth_info;
                var payModel = new ch_transfer {
                    businessnumber = model.order_no, subject = "电商的供应商货款", bankaccounttype = "储蓄卡",
                    transactionamount = (decimal.Parse(model.tran_amount) / 100).ToString("0.00"),
                    bankcardtype = auth_info.busi_type == 0 ? "个人" : "企业", bankcardnumber = auth_info.account_no,
                    bankcardname = auth_info.account_name, bankname = auth_info.bank_name, backurl = backurl, fromaccountnumber = ChPaySign.accountnumber
                    //, branchbankname = auth_info.branch_name, banknumber = auth_info.branch_code
                    , province = auth_info.province, city = auth_info.city
                };
                if (auth_info.busi_type == 1) {
                    payModel.branchbankname = auth_info.branch_name;
                    payModel.banknumber = auth_info.branch_code;
                }
#if DEBUG
                var apiResult = new ch_base_resp<ch_transfer_resp> { result = "success" };
                //var apiResult = await _chPaySign.PayGateway<ch_transfer_resp>(payModel);
#else
                var apiResult = new ch_base_resp<ch_transfer_resp> { result = "success" };
#endif
                int status = 0;//结算状态：1－到账成功，2－不确定,转账中，3－失败
                string msg = ""; string transaction_no = "";
                DateTime pay_time = DateTime.Now;
                if (apiResult != null) {
                    if (apiResult.result == "success") {
                        //转账中，到账以异步通知为准
                        status = 2; msg = "提现成功";
                        TransferStatus transferStatus = TransferStatus.Proceed;
                        _iTransferService.TransferSuccess(new platform_transfer {
                            pay_time = pay_time, transaction_no = transaction_no, status = transferStatus,
                            order_no = model.order_no, merchant_no = model.merchant_no
                        });
                    } else {
                        //代付失败，不生成账单和账
                        status = 3; msg = apiResult.msg;
                        _iTransferService.TransferFail(new platform_transfer {
                            pay_time = pay_time, transaction_no = transaction_no, status = TransferStatus.Fail,
                            order_no = model.order_no, merchant_no = model.merchant_no, fail = msg
                        });
                    }
                } else {
                    //代付失败，不生成账单和账
                    status = 3; msg = "代付请求失败";
                    _iTransferService.TransferFail(new platform_transfer {
                        pay_time = pay_time, transaction_no = transaction_no, status = TransferStatus.Fail,
                        order_no = model.order_no, merchant_no = model.merchant_no, fail = msg
                    });
                }
                return ApiResultToJson.Json(msg, new transfer_result {
                    order_no = model.order_no, transaction_no = transaction_no, pay_time = pay_time, status = status
                });
            } else {
                //次日代付，生成账单和账
                _iTransferService.ApplyTransfer(model);
                return ApiResultToJson.Json("提现进行中", new transfer_result { order_no = model.order_no, transaction_no = "", pay_time = null, status = 4 });
            }
        }

        /// <summary>
        /// 再原来提现单上重新代付
        /// </summary>
        /// <returns>The transfer.</returns>
        /// <param name="id">Identifier.</param>
        public async Task<transfer_result> ReTransfer(long id) {
            var transfer = _iTransferService.Get(id);
            var setting = _iSettingService.Get();
            var backurl = setting.site.api_url + "/pay/chpay_transfer_notify/" + transfer.merchant.merchant_no;
            var auth_info = transfer.binder.setting.auth_info;
            string pay_no = DateTime.Now.ToString("yyyyMMddHHmmssffff") + DtoHelper.RandCode(6);
            var payModel = new ch_transfer {
                businessnumber = pay_no, subject = "电商的供应商货款", bankaccounttype = "储蓄卡",
                transactionamount = transfer.transfer_amount.ToString("0.00"),
                bankcardtype = auth_info.busi_type == 0 ? "个人" : "企业", bankcardnumber = auth_info.account_no,
                bankcardname = auth_info.account_name, bankname = auth_info.bank_name, backurl = backurl, fromaccountnumber = ChPaySign.accountnumber,
                province = auth_info.province, city = auth_info.city
            };
            if (auth_info.busi_type == 1) {
                payModel.branchbankname = auth_info.branch_name;
                payModel.banknumber = auth_info.branch_code;//是支行行号还是银行行号
            }
            var isHEAD = false;
#if DEBUG
            var apiResult = new ch_base_resp<ch_transfer_resp> { result = "success" };
            backurl = setting.site.api_url + "/pay/chpay_transfer_notify2/" + transfer.merchant.merchant_no;
            isHEAD = true;
            //var apiResult = await _chPaySign.PayGateway<ch_transfer_resp>(payModel);
#else
            isHEAD = true;
            var apiResult = new ch_base_resp<ch_transfer_resp> { result = "success" };
            backurl = setting.site.api_url + "/pay/chpay_transfer_notify2/" + transfer.merchant.merchant_no;
#endif
            int status = 0;//结算状态：1－到账成功，2－不确定,转账中，3－失败
            string msg = ""; string transaction_no = "";
            DateTime pay_time = DateTime.Now;
            if (apiResult != null) {
                if (apiResult.result == "success") {
                    //转账中，到账以异步通知为准
                    status = 2; msg = "提现成功";
                    _iTransferService.ReTransfer(new re_transfer {
                        pay_time = pay_time, transaction_no = transaction_no, status = TransferStatus.Proceed, pay_no = pay_no,
                        order_no = transfer.order_no, auth_info = auth_info, merchant_no = transfer.merchant.merchant_no
                    });
                    if (isHEAD) {
                        var model = new ch_transfer_notify {
                            businessnumber = pay_no,
                            status = "成功",
                            inputdate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                        };
                        var result_success = await backurl.PostJsonAsync(model).ReceiveString();
                    }
                } else {
                    //代付失败，不生成账单和账
                    status = 3; msg = apiResult.msg;
                    _iTransferService.ReTransfer(new re_transfer {
                        pay_time = pay_time, transaction_no = transaction_no, status = TransferStatus.Fail, pay_no = pay_no,
                        order_no = transfer.order_no, fail = msg, auth_info = auth_info, merchant_no = transfer.merchant.merchant_no
                    });
                }
            } else {
                //代付失败，不生成账单和账
                status = 3;
                msg = "代付请求失败";
                _iTransferService.TransferFail(new platform_transfer {
                    pay_time = pay_time, transaction_no = transaction_no, status = TransferStatus.Fail,
                    order_no = transfer.order_no, fail = msg, merchant_no = transfer.merchant.merchant_no
                });
            }
            return ApiResultToJson.Json(msg, new transfer_result {
                order_no = transfer.order_no, transaction_no = transaction_no,
                pay_time = pay_time, status = status
            });
        }

        public async Task<transfer_result> TokenTransfer(long id) {
            var transfer = _iTokenTransferService.Get(id);
            if (transfer.status != TokenTransferStatus.PassedUnpaid)
                throw new ServerErrorException("提现单状态异常");
            var setting = _iSettingService.Get();
            var backurl = setting.site.api_url + "/pay/chpay_token_transfer_notify/" + transfer.merchant.merchant_no;
            var card = context.MerchantBankCard.FirstOrDefault(c => c.MerchantId == transfer.merchant_id);
            if (card == null || card.Status == EMerchantBankCardStatus.AuditFail || card.Status == EMerchantBankCardStatus.ToAudit)
                throw new ServerErrorException("银行卡未审核通过");
            string pay_no = DateTime.Now.ToString("yyyyMMddHHmmssffff") + DtoHelper.RandCode(6);
            var payModel = new ch_transfer {
                businessnumber = pay_no, subject = "电商的供应商货款", bankaccounttype = "储蓄卡",
                transactionamount = transfer.amount.ToString("0.00"),
                bankcardtype = transfer.busi_type == 0 ? "个人" : "企业", bankcardnumber = card.AccountNum,
                bankcardname = card.AccountName, bankname = card.BankName, backurl = backurl, fromaccountnumber = ChPaySign.accountnumber
            };
            int status = 0;//结算状态：1－到账成功，2－不确定,转账中，3－失败
            string msg = ""; string transaction_no = "";
            DateTime pay_time = DateTime.Now;
            var isHEAD = false;
#if DEBUG
            var apiResult = new ch_base_resp<ch_transfer_resp> { result = "success" };
            backurl = string.Format("{0}/pay/chpay_token_transfer_notify2/{1}", setting.site.api_url, transfer.merchant.merchant_no);
            isHEAD = true;
            //var apiResult = await _chPaySign.PayGateway<ch_transfer_resp>(payModel);
#else
            isHEAD = true;
            var apiResult = new ch_base_resp<ch_transfer_resp> { result = "success" };
            backurl = string.Format("{0}/pay/chpay_token_transfer_notify2/{1}", setting.site.api_url, transfer.merchant.merchant_no);
#endif

            if (apiResult != null) {
                if (apiResult.result == "success") {
                    //转账中，到账以异步通知为准
                    status = 2; msg = "提现成功";
                    _iTokenTransferService.ReTokenTransfer(new platform_transfer {
                        pay_time = pay_time, transaction_no = transaction_no, status = TransferStatus.Proceed, pay_no = pay_no,
                        order_no = transfer.order_no, merchant_no = transfer.merchant.merchant_no
                    });

                    //以下代码如果是通道可用就要注释掉
                    if (isHEAD) {
                        var model = new ch_transfer_notify {
                            businessnumber = pay_no,
                            status = "成功",
                            inputdate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                        };
                        var result_success = await backurl.PostJsonAsync(model).ReceiveString();
                    }
                } else {
                    //代付失败，不生成账单和账
                    status = 3; msg = apiResult.msg;
                    _iTokenTransferService.ReTokenTransfer(new platform_transfer {
                        pay_time = pay_time, transaction_no = transaction_no, status = TransferStatus.Fail, pay_no = pay_no,
                        order_no = transfer.order_no, fail = msg, merchant_no = transfer.merchant.merchant_no
                    });
                }
            } else {
                //代付失败，不生成账单和账
                status = 3;
                msg = "代付请求失败";
                _iTokenTransferService.TransferFail(new platform_transfer {
                    pay_time = pay_time, transaction_no = transaction_no, status = TransferStatus.Fail,
                    order_no = transfer.order_no, fail = msg, merchant_no = transfer.merchant.merchant_no
                });
            }
            return ApiResultToJson.Json(msg, new transfer_result {
                order_no = transfer.order_no, transaction_no = transaction_no,
                pay_time = pay_time, status = status
            });
        }

        /// <summary>
        /// 代付批处理:生成代付文件，将批号写入提现表，生成代付文件记录，并上传FTP，FTP成功调用代付通知，FTP失败提示手动上传，并去文件记录管理手动代付通知。
        /// </summary>
        /// <returns>The transfer.</returns>
        /// <param name="model">Model.</param>
        public async Task<batch_transfer_result> Transfer(batch_transfer model) {
            string batchNo = DateTime.Now.ToString("yyyyMMddHHmmssffff") + DtoHelper.RandCode(6);
            //string batchFileName = batchNo + ".txt";
            //model.batch_file = batchFileName;
            model.batch_no = batchNo;
            model.batch_file = "chpay";
            var dt = DateTime.Now;
            if (model.orders.Count >= 999)
                return ApiResultToJson.Json<batch_transfer_result>("代付报盘不得超过999笔");
            var payModel = new ch_batch_transfer {
                accountnumber = ChPaySign.accountnumber, batchno = batchNo, enterprisecode = ChPaySign.enterprisecode, paydate = dt.ToString("yyyyMMdd")
            };
            //生成代付
            List<string> rows = new List<string>();
            int i = 0;
            decimal batchamount = 0;
            foreach (var item in model.orders) {
                item.pay_no = DateTime.Now.ToString("yyyyMMddHHmmssffff") + DtoHelper.RandCode(6);
                //流水号1^商品名称1^收款方银行卡号1^收款账号姓名1^付款金额1^银行卡类型1^银行卡借贷类型1^银行名称1^支行1^省1^市1^联行号1^描述1^备注说明1
                if (item.busi_type == 0)
                    rows.Add(string.Format("{0}^{1}^{2}^{3}^{4}^{5}^{6}^{7}^{8}^{9}^{10}^{11}^{12}^{13} ",
                           item.pay_no, "电商的供应商货款", item.account_no, item.account_name,
                           (decimal.Parse(item.tran_amount) / 100).ToString("0.00"), "个人", "储蓄卡", item.bank_name, "", "", "", "", "", ""));
                else
                    rows.Add(string.Format("{0}^{1}^{2}^{3}^{4}^{5}^{6}^{7}^{8}^{9}^{10}^{11}^{12}^{13} ",
                           item.pay_no, "电商的供应商货款", item.account_no, item.account_name,
                           (decimal.Parse(item.tran_amount) / 100).ToString("0.00"), "企业", "储蓄卡",
                           item.bank_name, item.branch_name, item.province, item.city, item.branch_code, "", ""));
                batchamount += decimal.Parse(item.tran_amount) / 100M;
                i++;
            }
            payModel.batchnum = i;
            payModel.batchamount = batchamount.ToString("0.00");
            payModel.paydetail = rows.Aggregate((k, v) => k + "|" + v);
            //商户申请批号写入库
            var setting = _iSettingService.Get();
            var backurl = setting.site.api_url + "/pay/chpay_batchtransfer_notify";
            payModel.backurl = backurl;
            var batchId = _iTransferService.ApplyTransfer(model);
            if (batchId > 0) {
                var apiResult = await _chPaySign.PayGateway<string>(payModel);
                if (apiResult != null) {
                    if (apiResult.result == "success") {
                        _iTransferService.UpdateBatch(batchId, "", TransferBatchStatus.Notify);
                        return ApiResultToJson.Json("提交成功", new batch_transfer_result { batch_no = model.batch_no, status = 1 });
                    } else {
                        return ApiResultToJson.Json<batch_transfer_result>(apiResult.msg);
                    }
                }
            }
            return ApiResultToJson.Json<batch_transfer_result>("批处理报盘失败");
        }

        /// <summary>
        /// 提交代付批处理报盘通知（批量代付异步通知用）
        /// </summary>
        /// <returns>The transfer.</returns>
        /// <param name="batchId">Batch Id.</param>
        public async Task<int> TransferNotify(long batchId, string transferResult, long merchant_id) {
            var platform_transfers = new List<platform_transfer>();
            var data = transferResult.Split('|');
            foreach (var row in data) {
                if (string.IsNullOrEmpty(row)) continue;
                var rowData = row.Split('^');
                //流水号^收款方账号^收款账号姓名^付款金额^成功标识(成功)^成功原因(null)^传化支付内部流水号^完成时间。
                //流水号^收款方账号^收款账号姓名^付款金额^失败标识(失败)^失败原因^传化支付内部流水号^完成时间。
                TransferStatus transferStatus = TransferStatus.None;
                var respCode = rowData[4];
                if (respCode == "成功") {
                    transferStatus = TransferStatus.Finish;
                } else {
                    transferStatus = TransferStatus.Fail;
                }
                platform_transfers.Add(new platform_transfer {
                    //完成时间格式不知道
                    order_no = rowData[0], pay_time = rowData[7].ToDateTime(),
                    transaction_no = rowData[6], fail = rowData[5], status = transferStatus
                });
            }
            var result = _iTransferService.Transfer(platform_transfers, batchId, TransferBatchStatus.Treat, "CHPAY");
            return await Task.FromResult(result);
        }

        /// <summary>
        /// 提交代付批处理查询
        /// </summary>
        /// <returns>The transfer.</returns>
        /// <param name="batchId">Batch Id.</param>
        /// <param name="noticeTranId">报盘通知交易流水号</param>
        public async Task<int> TransferBack(long batchId, string noticeTranId, long merchant_id) {
            var transferBatch = _iTransferService.GetBatch(batchId);
            var payModel = new ch_batch_transfer_query { batchno = transferBatch.batch_no };
            var apiResult = await _chPaySign.PayGateway<List<ch_batch_transfer_result>>(payModel);
            if (apiResult != null) {
                if (apiResult.result == "success" && transferBatch.status != TransferBatchStatus.Treat) {
                    var platform_transfers = new List<platform_transfer>();
                    foreach (var row in apiResult.data) {
                        string respCode = row.status;
                        TransferStatus transferStatus = TransferStatus.None;
                        if (respCode == "成功") {
                            transferStatus = TransferStatus.Finish;
                        } else if (respCode == "待处理") {
                            transferStatus = TransferStatus.UnConfirm;
                        } else {
                            transferStatus = TransferStatus.Fail;
                        }
                        DateTime? pay_time = null;
                        if (!string.IsNullOrEmpty(row.stampDate)) pay_time = row.stampDate.ToDateTime();
                        platform_transfers.Add(new platform_transfer {
                            order_no = row.businessNumber, pay_time = pay_time,
                            transaction_no = row.payBusinessNumber, fail = row.dealResult, status = transferStatus
                        });
                    }
                    var result = _iTransferService.Transfer(platform_transfers, batchId, TransferBatchStatus.Treat, "CHPAY");
                    return result;
                }
                return 0;
            }
            return 0;
        }

        /// <summary>
        /// 单笔代付查询
        /// </summary>
        /// <returns>The query.</returns>
        /// <param name="model">Model.</param>
        public async Task<transfer_result> TransferQuery(transfer_query model) {
            transfer_dto order = null;
            if (!string.IsNullOrEmpty(model.order_no)) order = _iTransferService.Get(model.merchant_no, model.order_no);
            else order = _iTransferService.GetByTran(model.transaction_no);
            DateTime pay_time = order.pay_info.pay_time.HasValue ? order.pay_info.pay_time.Value : order.apply_time;
            var payModel = new ch_transfer_query { businessnumber = order.pay_info.pay_no };
            var apiResult = await _chPaySign.PayGateway<ch_transfer_queryresult>(payModel);
            int status = (int)order.status;//结算状态：1－到账成功，2－不确定，3－失败
            string transaction_no = order.pay_info.transaction_no;
            string msg = "";
            if (apiResult != null) {
                if (apiResult.result == "success") {
                    //代付成功
                    if (apiResult.data.status == "成功") {
                        status = 1; msg = "提现成功";
                        //只处理不确定的状态为成功，因为账在上代付已扣
                        if (order.status != TransferStatus.Finish) {
                            transaction_no = apiResult.data.businessrecordnumber;
                            _iTransferService.TransferSuccess(new platform_transfer {
                                pay_time = pay_time, transaction_no = apiResult.data.businessrecordnumber,
                                order_no = order.order_no, status = TransferStatus.Finish, merchant_no = model.merchant_no
                            });
                        }
                    } else {
                        //代付失败
                        status = 3; msg = apiResult.msg;
                    }
                } else {
                    //代付失败
                    status = 3; msg = string.IsNullOrEmpty(order.fail) ? apiResult.msg : order.fail;
                }
            } else {
                //代付失败
                status = 3; msg = order.fail;
            }
            return ApiResultToJson.Json(msg, new transfer_result {
                order_no = order.order_no, transaction_no = transaction_no, pay_time = pay_time, status = status
            });
        }
        /// <summary>
        /// token单笔代付查询
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<transfer_result> TokenTransferQuery(transfer_query model) {
            if (string.IsNullOrEmpty(model.order_no))
                throw new ServerErrorException("请输入订单号");
            var order = _iTokenTransferService.Get(model.merchant_no, model.order_no);
            DateTime pay_time = order.pay_info.pay_time.HasValue ? order.pay_info.pay_time.Value : order.apply_time;
            var payModel = new ch_transfer_query { businessnumber = order.pay_info.pay_no };
            var apiResult = await _chPaySign.PayGateway<ch_transfer_queryresult>(payModel);
            int status = (int)order.status;//结算状态：1－到账成功，2－不确定，3－失败
            string transaction_no = order.pay_info.transaction_no;
            string msg = "";
            if (apiResult != null) {
                if (apiResult.result == "success") {
                    //代付成功
                    if (apiResult.data.status == "成功") {
                        status = 1; msg = "提现成功";
                        //只处理不确定的状态为成功，因为账在上代付已扣
                        if (order.status != TokenTransferStatus.Passedpaid) {
                            transaction_no = apiResult.data.businessrecordnumber;
                            _iTokenTransferService.TransferSuccess(new platform_transfer {
                                pay_time = pay_time, transaction_no = apiResult.data.businessrecordnumber,
                                order_no = order.order_no, status = TransferStatus.Finish, merchant_no = model.merchant_no
                            });
                        }
                    } else {
                        //代付失败
                        status = 3; msg = apiResult.msg;
                    }
                } else {
                    //代付失败
                    status = 3; msg = string.IsNullOrEmpty(order.msg) ? apiResult.msg : order.msg;
                }
            } else {
                //代付失败
                status = 3; msg = order.msg;
            }
            return ApiResultToJson.Json(msg, new transfer_result {
                order_no = order.order_no, transaction_no = transaction_no, pay_time = pay_time, status = status
            });
        }
#endregion

#region 代收,T+1转账-不可用
        /// <summary>
        /// 代收签约
        /// </summary>
        /// <returns>The receive.</returns>
        /// <param name="model">Model.</param>
        public Task<ApiResultMessage> InsteadReceive(verify_model model) {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 代收签约
        /// </summary>
        /// <returns>The receive.</returns>
        /// <param name="model">Model.</param>
        public Task<ApiResultMessage> InsteadReceive(verify_model_sms model) {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 单笔代收
        /// </summary>
        /// <returns>The transfer.</returns>
        /// <param name="model">Model.</param>
        public Task<transfer_result> AgencyFund(apply_receive model) {
            throw new NotImplementedException();
        }
#endregion

#region 商户进件－不可用
        /// <summary>
        /// 返回的是第三方的商户号，opt：A增加，M修改
        /// </summary>
        /// <returns>The register.</returns>
        /// <param name="dto">Dto.</param>
        /// <param name="opt">A增加，M修改.</param>
        public Task<merchant_register_result> MerchantRegister(merchant_register_model dto, string opt) {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 新增商户进件
        /// </summary>
        /// <returns>The register.</returns>
        /// <param name="bind_id">Bind identifier.</param>
        public Task<merchant_register_result> MerchantRegister(long bind_id, string settle_type, PayChannel channel = PayChannel.None) {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 编辑商户进件
        /// </summary>
        /// <returns>The modify.</returns>
        /// <param name="bind_id">Bind identifier.</param>
        public Task<merchant_register_result> MerchantModify(long bind_id, string settle_type, PayChannel channel = PayChannel.None) {
            throw new NotImplementedException();
        }
#endregion

#region 对账
        //public async Task<int> ItpToFile(DateTime create_date) {
        //	var payModel = new cn_tip_req();
        //	payModel.dog_ak = ChPaySign.ak;
        //	payModel.enterprisecode = ChPaySign.enterprisecode;
        //	payModel.statementdate = create_date.ToString("yyyyMMdd");
        //	var apiResult = await _chPaySign.DownLoad(payModel);
        //	if (apiResult != null) {
        //		var result = _iProfitDayService.Insert(new profit_day_dto {
        //			create_date = create_date, file = apiResult, status = 1, pay_channel = PayChannel.ChPay
        //		});
        //		return result;
        //	}
        //	return 0;
        //}
        public int DealItp(long id) {
            throw new NotImplementedException();
        }
#endregion

#region 四要素
        /// <summary>
        /// 四要素
        /// </summary>
        /// <returns>The verify.</returns>
        /// <param name="dto">Model.</param>
        public Task<certify_verify_result> CertifyVerify(certify_verify dto) {
            throw new NotImplementedException();
        }

        public Task<mall_result> MallPay(mall_model obj) {
            throw new NotImplementedException();
        }

        public Task<int> ItpToFile(DateTime create_date) {
            throw new NotImplementedException();
        }
#endregion
    }
}